#ifndef FILETRANSFER_H
#define FILETRANSFER_H

#include <QObject>
#include <QFile>
#include <QQueue>
#include <QScopedPointer>

class QTimer;
class QProgressDialog;
class Protocol;

struct TransferItem {
    QString localPath;
    QString remotePath;
    qint64 size;
    qint64 transferred;
    bool isUpload;  // true为上传，false为下载
    int id;
};

class FileTransferService : public QObject
{
    Q_OBJECT

public:
    explicit FileTransferService(QObject *parent = nullptr);
    ~FileTransferService();

    // 设置协议处理器
    void setProtocol(Protocol *protocol);
    
    // 文件传输操作
    int uploadFile(const QString &localPath, const QString &remotePath);
    int downloadFile(const QString &remotePath, const QString &localPath);
    void cancelTransfer(int transferId);
    void cancelAllTransfers();
    
    // 获取传输状态
    QList<TransferItem> getPendingTransfers() const;
    QList<TransferItem> getActiveTransfers() const;

signals:
    void transferStarted(int transferId);
    void transferProgress(int transferId, qint64 transferred, qint64 total);
    void transferFinished(int transferId, bool success, const QString &errorString);
    void transferCanceled(int transferId);

public slots:
    void pauseTransfer(int transferId);
    void resumeTransfer(int transferId);

private slots:
    void processNextTransfer();
    void onTransferDataReceived(const QByteArray &data);
    void onTransferCompleted(int transferId, bool success, const QString &error);
    void updateProgress();

private:
    void startTransfer(TransferItem &item);
    void cleanupTransfer(int transferId);
    
    Protocol *protocol;
    QQueue<TransferItem> pendingTransfers;
    QMap<int, TransferItem> activeTransfers;
    QMap<int, QFile*> transferFiles;
    
    QTimer *processTimer;
    QTimer *progressTimer;
    int nextTransferId;
    
    // UI相关
    QProgressDialog *progressDialog;
};

#endif // FILETRANSFER_H